﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BestPrice.Core
{
    public class ManagerFactory
    {
        public static IBaseManager Locate(Type type)
        {
            if (type.IsInterface)
            {
                String typename = GetFullNameFromInterface(type.FullName);
                return (IBaseManager)Activator.CreateInstance(ResolveType(type.FullName));
            }
            else
            {
                return (IBaseManager)Activator.CreateInstance(type);
            }
        }

        public static Dictionary<Type, IBaseManager> Managers = new Dictionary<Type, IBaseManager>();
        
        public static T Locate<T>()
        {
            if (typeof(T).IsInterface)
                return (T)Activator.CreateInstance(ResolveType(GetFullNameFromInterface<T>()));
            else
                return Activator.CreateInstance<T>();
        }

        public static Type ResolveType(String fullName)
        {
            Type type;
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            foreach (var assembly in assemblies)
            {
                type = assembly.GetType(fullName, false, false);
                if (type != null)
                    return type;
            }

            return null;
        }

        private static String GetFullNameFromInterface<T>()
        {
            var ifullname = typeof(T).FullName;
            int i = ifullname.LastIndexOf('.');
            return ifullname.Substring(0, i) + ".Implement." + ifullname.Substring(i + 2);
        }

        private static String GetFullNameFromInterface(String ifullname)
        {
            int i = ifullname.LastIndexOf('.');
            return ifullname.Substring(0, i) + "." + ifullname.Substring(i + 2);
        }
    }
}
